﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using net.veekee.common;
using net.veekee.common.data.csv;
using System.Collections;
using net.veekee.logprocessor.plugin.output;

namespace net.veekee.logprocessor.plugin.output.pack
{
    class CSVWriter : AWriter
    {
        private CSVWriterFile csv = null;

        public override bool Load(String filename)
        {
            try
            {
                this.FileName = filename;
                String separator = Options.GetInstance().Get("output.csv.separator", ";");
                if (separator.Length == 0)
                    separator = ";";
                this.csv = new CSVWriterFile(this.FileName, Encoding.GetEncoding(this.context.Encoding), separator[0], this.context.Append);

                this.csv.SelectSheet("interceptor");

                this.WriteHeader();
                return this.csv.IsValid;
            }
            catch (Exception e)
            {
                Log.GetInstance().Error(e.ToString());
                this.WriteFooter();
            }
            return false;
        }

        protected override void AddLine(IEnumerator items)
        {
            if (!this.csv.IsValid)
                return;
            this.csv.SetLine(ulong.MinValue, items);
        }

        public override void WriteFooter()
        {
            if (!this.csv.IsValid)
                return;
            this.csv.Save();
        }

        public override void Dispose()
        {
            if (this.csv != null)
            {
                this.WriteFooter();
                this.csv.Dispose();
            }
        }
    }
}
